package com.example.spider.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ser.std.ByteArraySerializer;
import net.jpountz.lz4.LZ4Factory;

import java.io.IOException;
import java.util.BitSet;

public class BitSetSerializer extends JsonSerializer<BitSet> {

    public static final BitSetSerializer INSTANCE = new BitSetSerializer();

    private final ByteArraySerializer jacksonByteArraySerializer = new ByteArraySerializer();

    @Override
    public void serialize(BitSet value, com.fasterxml.jackson.core.JsonGenerator gen,
                          com.fasterxml.jackson.databind.SerializerProvider serializers) throws IOException, JsonProcessingException {

        byte[] noCompressed = value.toByteArray();
        byte[] compressed = LZ4Factory.fastestInstance().fastCompressor().compress(noCompressed);
        byte[] toWrite = new byte[compressed.length + 2];
        int length = noCompressed.length;
        toWrite[0] = (byte) (length >> 8 & 0xFF);
        toWrite[1] = (byte) (length & 0xFF);
        System.arraycopy(compressed, 0, toWrite, 2, compressed.length);

        jacksonByteArraySerializer.serialize(toWrite, gen, serializers);

    }

}